package com.antdant.service;

import com.antdant.config.ConfigInfo;
import com.antdant.exception.GeneralException;
import com.antdant.model.SmsSendDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @Author Lee Yunc
 * @Date 2021/2/24 16:01
 * @Description: 像邮箱发送验证码服务
 * @Version 1.0
 */
@Service
@Slf4j
public class SmsService {

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private ConfigInfo configInfo;

    /**
     * 发送文本类邮件
     *
     * @param smsSendDto
     */
    public void sendSimpleTextMail(SmsSendDto smsSendDto) {
        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(configInfo.getEmailFromUser());
            simpleMailMessage.setTo(smsSendDto.getToUser());
            simpleMailMessage.setSubject(smsSendDto.getSubject());
            simpleMailMessage.setText(smsSendDto.getTextContent());
            javaMailSender.send(simpleMailMessage);
        } catch (Exception e) {
            log.error("sendSimpleTextMail failed,Error:", e);
            throw new GeneralException("邮件发送失败，请稍后重试！");
        }
    }

    public void sendMimeTextMail(SmsSendDto smsSendDto) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(configInfo.getEmailFromUser());
            helper.setTo(smsSendDto.getToUser());
            helper.setSubject(smsSendDto.getSubject());
            helper.setText(smsSendDto.getTextContent(), true);
            javaMailSender.send(message);

        } catch (MessagingException e) {
            log.error("sendMimeTextMail failed,Error:", e);
            throw new GeneralException("邮件发送失败，请稍后重试");
        }
    }
}
